package com.webserver.controller;

import com.webserver.annotation.Controller;
import com.webserver.annotation.RequestMapping;
import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;
import qrcode.QRCodeUtil;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@Controller
public class ToolsController {
    //参数1:二维码上包含的文本信息 参数2:图片生成的位置
    //QRCodeUtil.encode(message,"./qr.jpg");
    //参数1:二维码上包含的文本信息 参数2:图片生成后会通过该流写出
    //QRCodeUtil.encode(message,new FileOutputStream("./qr.jpg"));
    ////参数1:二维码上包含的文本信息 参数2:二维码中间的logo 参数3:图片生成的位置 参数4:
    //是否需要压缩logo图片到中间位置
    @RequestMapping("/myweb/createQr")
    public void creatQr(HttpServletRequest request, HttpServletResponse response){
        String message=request.getParameter("content");
        try {
            QRCodeUtil.encode(message,response.getOutputStream());
            response.setContentType("image/jpeg");
            System.out.println("二维码生成完毕");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @RequestMapping("/myweb/random.jpg")
    public void creatRandomImage(HttpServletRequest request,HttpServletResponse response){
        BufferedImage image=new BufferedImage(70,30,BufferedImage.TYPE_INT_RGB);
        Graphics g=image.getGraphics();
        String line="abcdefghjkmnopkrstuvwkyz0123456789ABCDEFGHIJKLMNOPKRSTUVWKYZ";
        Random random=new Random();

        Color bgcolor=new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256));
        g.setColor(bgcolor);
        g.fillRect(0,0,70,30);
        for (int i=0;i<4;i++){
            String str=line.charAt(random.nextInt(line.length()))+"";
            switch (random.nextInt(2)){
                case 0:g.setColor(Color.BLUE); break;
                case 1:g.setColor(Color.red); break;
            }
            g.setFont(new Font(Font.DIALOG, Font.BOLD, 18));
            g.drawString(str,i*15+5,20+random.nextInt(7)-3);
        }
        //两条干扰线
        for (int i = 0; i < 2; i++) {
            Color color = new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
            g.setColor(color);
            g.drawLine(random.nextInt(71),random.nextInt(31),
                    random.nextInt(71),random.nextInt(31));
        }
        try {
            ImageIO.write(image,"jpg",response.getOutputStream());
            response.setContentType("image/jpeg");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
